import axios from 'axios'
import { elNotification } from '@/hooks/elNotification'
import { getToken } from '@/hooks/cookies'
import { useUserStore } from '@/stores/user'


const service = axios.create({
    baseURL: "/api",
})

// 请求拦截器
service.interceptors.request.use(function (config) {

    // 请求自动传入token到请求头
    const token = getToken()
    if (token) {
        config.headers["token"] = token
    }

    return config;
}, function (error) {
    return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(function (response) {
    return response.request.responseType == "blob" ? response.data : response.data.data;
}, function (error) {
    const userStore = useUserStore()
    const msg = error.response.data.msg || '请求失败'
    if (msg == "非法token，请先登录！") {
        userStore.logout().finally(() => location.reload())
    }
    elNotification(error.response.data.msg || '请求失败', 'error')
    return Promise.reject(error);
});

export default service